<template>
  <div class="search-suggestion">
    <van-cell icon="search" v-for="(text, index) in suggestions" :key="index">
      <div v-html="highlight(text)" slot="title"></div>
    </van-cell>

  </div>
</template>

<script>
import { getSearchSuggestions } from '../../../api/search'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: ''
    }
  },
  watch: {
    searchText: {
      // 当 searchText 发生变化的时候会调用 handler 函数（固定的）
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value)
      }, 200),
      // 第一次的时候也触发 handler
      immediate: true
    }
  },
  methods: {
    async loadSearchSuggestions (q) {
      try {
        const { data } = await getSearchSuggestions(q)
        this.suggestions = data.data.options
      } catch (error) {
        this.$toast('数据获取失败')
      }
    },
    highlight (text) {
      const newStr = this.searchText.replace(/([+?|])/g, '\\$1')
      const reg = new RegExp(newStr, 'gi')
      return text.replace(reg, `<span class='active'>${this.searchText}</span>`)
    }
  }
}
</script>

<style lang="less" scoped>
.search-suggestion {
  /deep/ span.active {
    color: #3296fa;
  }
}
</style>
